package com.itwlj.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itwlj.constant.MessageConstant;
import com.itwlj.dto.SpecValueDTO;
import com.itwlj.dto.SpecValuePageQueryDTO;
import com.itwlj.entity.SpecValue;
import com.itwlj.exception.DeletionNotAllowedException;
import com.itwlj.mapper.SpecValueLinksMapper;
import com.itwlj.mapper.SpecValueMapper;
import com.itwlj.result.PageResult;
import com.itwlj.service.SpecValueService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 规格值业务层
 */
@Service
public class SpecValueServiceImpl implements SpecValueService {

    @Autowired
    private SpecValueMapper specValueMapper;
    @Autowired
    private SpecValueLinksMapper specValueLinksMapper;

    /**
     * 新增规格值
     *
     * @param specValueDTO
     */
    public void insert(SpecValueDTO specValueDTO) {
        SpecValue specValue = new SpecValue();
        BeanUtils.copyProperties(specValueDTO, specValue);
        specValueMapper.insert(specValue);
    }

    /**
     * 规格值分页查询
     *
     * @param specValuePageQueryDTO
     * @return
     */
    public PageResult pageQuery(SpecValuePageQueryDTO specValuePageQueryDTO) {
        PageHelper.startPage(specValuePageQueryDTO.getPage(), specValuePageQueryDTO.getPageSize());

        Page<SpecValue> page = specValueMapper.pageQuery(specValuePageQueryDTO);

        long total = page.getTotal();
        List<SpecValue> records = page.getResult();

        return new PageResult(total, records);
    }

    /**
     * 规格批量删除
     *
     * @param ids
     */
    public void deleteBatch(List<Long> ids) {
        if (specValueLinksMapper.getBySpecValueId(ids) > 0){
            throw new DeletionNotAllowedException(MessageConstant.SPEC_VALUE_BE_RELATED_BY_SPEC);
        }

        specValueMapper.deleteBatch(ids);
    }

    /**
     * 查询规格值
     *
     * @return
     */
    public List<SpecValue> list() {
        List<SpecValue> specValueList = specValueMapper.list();
        return specValueList;
    }
}
